<template>
    <div>
        <h3 style="text-align: center;">档案名称：【{{ archive.name }}】</h3>
        <el-divider />
        <!-- 使用element plus的网格布局方式把下面的区域分为两列，左边展示档案目录，右边展示目录里面的文件列表 -->
        <el-row :gutter="2">
            <el-col :span="5">
                <el-card style="max-width: 100%;">
                    <template #header>
                        <div class="card-header"
                            style="display: flex; flex-direction: row;justify-content: space-between; align-items: center;">
                            <el-text size="large" tag="b">档案目录结构</el-text>
                            <!-- <el-link type="primary" size="mini" @click="updateArchiveDirectory">保存挂接状态</el-link> -->
                        </div>
                    </template>
                    <el-tree :data="dataSource" node-key="id" default-expand-all :highlight-current="true"
                        :expand-on-click-node="false" icon="Folder" @node-click="handleNodeClick">
                        <template #default="{ node, data }">
                            <span class="custom-tree-node">
                                <span>{{ data.id }}-{{ data.label }}</span>
                            </span>
                        </template>
                    </el-tree>
                </el-card>
            </el-col>
            <el-col :span="19">
                <el-table v-loading="loading" :data="documentList">
                    <el-table-column label="主键" align="center" prop="id" />
                    <el-table-column label="文件名称" align="center" prop="name" />
                    <el-table-column label="当前所在目录" align="center">
                        <template #default="scope">
                            <el-text class="mx-1" size="large" v-if="scope.row.directory"><el-icon :size="15">
                                    <Folder />
                                </el-icon>{{ scope.row.directory }}</el-text>
                            <el-text class="mx-1" size="normal" v-else>未指定目录</el-text>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                        <template #default="scope">
                            <el-button link type="primary" @click="handleDirectoryChange(scope.row)"
                                v-hasPermi="['manage:archive:edit']">修改目录</el-button>
                            <el-button link type="primary" @click="handleDocumentDetail(scope.row)"
                                v-hasPermi="['manage:document:query']">查看文档</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                    v-model:limit="queryParams.pageSize" @pagination="getDocumentList" />
            </el-col>
        </el-row>
        <!-- 添加或修改文档目录的对话框 -->
        <el-dialog title="为文档挂接档案目录" v-model="open" width="500px" append-to-body>
            <el-form>
                <el-form-item label="文档名称">
                    <el-input v-model="selectedDocument.name"></el-input>
                </el-form-item>
                <el-form-item label="档案目录">
                    <el-select v-model="selectedDirectory" placeholder="Select" size="large" style="width: 240px">
                        <el-option v-for="item in directoryIdLabels" :key="item.id" :label="item.id + '-' + item.label"
                            :value="item.id" /> <!-- value 改为仅包含 id -->
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button class="ml-2" type="default" @click="open = false">取 消</el-button>
                    <el-button class="ml-2" type="primary" @click="saveDocumentDirectory">确 定</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import { getArchive, updateArchive, deleteDirectoryFiles, addDirectoryFiles } from "@/api/manage/archive";
import { listDocument, updateDocument } from "@/api/manage/document";

const { proxy } = getCurrentInstance();

const route = useRoute();

const archive = ref({});
const dataSource = ref([]);
const directoryIdLabels = ref([]);
const documentList = ref([]);
const selectedDirectory = ref("");
const selectedDocument = ref("");
const loading = ref(true);
const open = ref(false);
const total = ref(0);
const queryParams = ref({
    archiveId: route.query.id,
    pageNum: 1,
    pageSize: 10,
});

const oldData = ref({});
const newData = ref({});

const handleNodeClick = (data) => {
    console.log(data)
}


//  该函数接受一个树形结构的数据作为参数，并返回一个包含所有 id和label 值的数组
function extractIdLabels(tree) {
    let id_labels = [];

    function traverse(node) {
        if (node.id && node.label) {
            id_labels.push({ "id": node.id, "label": node.label });
        }
        if (node.children && node.children.length > 0) {
            node.children.forEach(child => traverse(child));
        }
    }

    tree.forEach(node => traverse(node));
    return id_labels;
}
// 函数通过递归遍历树形结构，找到与给定 id_label 对应的节点，并将文件 id 添加到该节点的 files 数组中。如果 files 数组不存在，则会先初始化为空数组。
function addFileToDirectory(tree, directoryId, fileId) {
    function traverse(node) {
        if (node.id === directoryId) { // 直接匹配 id
            if (!node.files) {
                node.files = [];
            }
            node.files.push(fileId);
            return true;
        }
        if (node.children && node.children.length > 0) {
            for (let child of node.children) {
                if (traverse(child)) {
                    return true;
                }
            }
        }
        return false;
    }

    tree.forEach(node => traverse(node));
}

function getDocumentList() {
    loading.value = true;
    listDocument(queryParams.value).then(response => {
        documentList.value = response.rows;
        total.value = response.total;
        loading.value = false;
    });
}

onMounted(() => {
    const archiveId = route.query.id;
    getArchive(archiveId).then(response => {
        archive.value = response.data;
        dataSource.value = JSON.parse(archive.value.directory);
        directoryIdLabels.value = extractIdLabels(dataSource.value);
    });
    getDocumentList();
});


/** 把挂接了文档的档案目录结构保存到数据库 */
function updateArchiveDirectory() {
    archive.value.directory = JSON.stringify(dataSource.value);
    updateArchive(archive.value).then(response => {
        ElMessage({ message: '档案目录已经更新!', type: 'success', duration: 1000 })
    });
}

/** 把文档的ID写入档案目录结构 */
function saveDocumentDirectory() {
    // selectedDocument.value.directory = parseInt(selectedDirectory.value); // 保存为整型
    // open.value = false;
    // addFileToDirectory(dataSource.value, parseInt(selectedDirectory.value), selectedDocument.value.id); // 调用时传入整型
    // console.log(dataSource.value);
    open.value = false;
    oldData.value = selectedDocument.value,
        console.log(oldData.value);
    newData.value = {
        ...selectedDocument.value,
        directory: parseInt(selectedDirectory.value)
    }
    deleteDirectoryFiles(oldData.value).then(res => {
        addDirectoryFiles(newData.value).then(response => {
            console.log('Directory updated successfully:', newData.value);
        }).catch(error => {
            console.error('Error updating directory:', error);
        });
    });

    updateDocument(newData.value).then(response => {
        ElMessage({ message: '文档已经挂接到指定的目录!', type: 'success', duration: 1000 });
        getDocumentList();
        // updateArchiveDirectory();
    });
}

function handleDocumentDetail(row) {
    proxy.$router.push({ path: "/manage/document/doc-detail", query: { id: row.id } });
}
//   修改文档所在目录
function handleDirectoryChange(row) {
    open.value = true;
    selectedDocument.value = row;
}
</script>

<style scoped>
.custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 16px;
    padding-right: 10px;
}
</style>